// popup.js - 弹出窗口的交互逻辑
document.addEventListener('DOMContentLoaded', function() {
    const convertBtn = document.getElementById('convertBtn');
    const copyBtn = document.getElementById('copyBtn');
    const status = document.getElementById('status');
    const loading = document.getElementById('loading');
    
    let convertedMarkdown = '';
    
    // 检查当前页面是否为语雀文档
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        const currentTab = tabs[0];
        
        if (currentTab.url && currentTab.url.includes('yuque.com')) {
            // 检查是否为文档页面
            if (currentTab.url.match(/yuque\.com\/.*\/.*\/.*/) || 
                currentTab.url.includes('/docs/')) {
                status.textContent = '✅ 已检测到语雀文档页面';
                status.style.background = 'rgba(34, 197, 94, 0.2)';
                convertBtn.disabled = false;
            } else {
                status.textContent = '⚠️ 请打开具体的语雀文档页面';
                status.style.background = 'rgba(251, 146, 60, 0.2)';
            }
        } else {
            status.textContent = '❌ 请在语雀文档页面使用此插件';
            status.style.background = 'rgba(239, 68, 68, 0.2)';
        }
    });
    
    // 转换按钮点击事件 - 一键转换+复制
    convertBtn.addEventListener('click', function() {
        convertBtn.disabled = true;
        loading.style.display = 'block';
        status.textContent = '🔄 正在解析文档内容...';
        
        // 向当前页面的content script发送消息
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {
                action: 'convertToMarkdown'
            }, function(response) {
                loading.style.display = 'none';
                
                if (chrome.runtime.lastError) {
                    console.error('发送消息失败:', chrome.runtime.lastError);
                    status.textContent = '❌ 转换失败：请刷新页面后重试';
                    status.style.background = 'rgba(239, 68, 68, 0.2)';
                    convertBtn.disabled = false;
                    return;
                }
                
                if (response && response.success) {
                    convertedMarkdown = response.markdown;
                    
                    // 直接复制到剪贴板
                    navigator.clipboard.writeText(convertedMarkdown).then(function() {
                        status.textContent = '✅ 转换成功！Markdown已复制到剪贴板';
                        status.style.background = 'rgba(34, 197, 94, 0.2)';
                        convertBtn.textContent = '🔄 重新转换并复制';
                        convertBtn.disabled = false;
                        
                        // 显示复制按钮以备用
                        copyBtn.style.display = 'inline-block';
                        copyBtn.disabled = false;
                    }).catch(function(err) {
                        console.error('复制失败:', err);
                        status.textContent = '✅ 转换成功！请点击复制按钮';
                        status.style.background = 'rgba(34, 197, 94, 0.2)';
                        copyBtn.style.display = 'inline-block';
                        copyBtn.disabled = false;
                        convertBtn.textContent = '🔄 重新转换并复制';
                        convertBtn.disabled = false;
                    });
                } else {
                    const errorMsg = response?.error || '未知错误';
                    status.textContent = `❌ 转换失败: ${errorMsg}`;
                    status.style.background = 'rgba(239, 68, 68, 0.2)';
                    convertBtn.disabled = false;
                }
            });
        });
    });
    
    // 复制按钮点击事件
    copyBtn.addEventListener('click', function() {
        if (convertedMarkdown) {
            navigator.clipboard.writeText(convertedMarkdown).then(function() {
                const originalText = copyBtn.textContent;
                copyBtn.textContent = '✅ 已复制!';
                copyBtn.classList.add('success');
                
                setTimeout(function() {
                    copyBtn.textContent = originalText;
                    copyBtn.classList.remove('success');
                }, 2000);
                
                status.textContent = '📋 Markdown已复制到剪贴板';
                status.style.background = 'rgba(34, 197, 94, 0.2)';
            }).catch(function(err) {
                console.error('复制失败:', err);
                status.textContent = '❌ 复制失败，请手动复制';
                status.style.background = 'rgba(239, 68, 68, 0.2)';
            });
        }
    });
    
    // 监听来自content script的消息
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.action === 'updateStatus') {
            status.textContent = request.message;
            if (request.type === 'error') {
                status.style.background = 'rgba(239, 68, 68, 0.2)';
            } else if (request.type === 'success') {
                status.style.background = 'rgba(34, 197, 94, 0.2)';
            }
        }
    });
});

// 记录插件使用情况
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'logUsage') {
        console.log('插件使用记录:', request.data);
    }
}); 